using UnityEngine;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Newtonsoft.Json;

namespace CalmNine.Framework
{
    public class PlayerPrefsListVal<T> : EventVal<ObservableList<T>>, IGameSave where T : class, INotifyPropertyChanged
    {
        private readonly string mSaveKey;

        public PlayerPrefsListVal(string saveKey)
        {
            mSaveKey = saveKey;
            mValue = new ObservableList<T>();

            // 从PlayerPrefs加载序列化的数据
            string savedData = PlayerPrefs.GetString(saveKey, string.Empty);
            if (!string.IsNullOrEmpty(savedData))
            {
                try
                {
                    List<T> items = JsonUtil.ConvertToObj<List<T>>(savedData);
                    foreach (T item in items)
                    {
                        mValue.Add(item);
                    }
                }
                catch (Exception e)
                {
                    Debug.LogError($"Failed to deserialize list data for key {saveKey}: {e.Message}");
                }
            }

            // 注册集合变更事件
            mValue.OnItemAdded += OnItemChanged;
            mValue.OnItemRemoved += OnItemChanged;
            mValue.OnItemChanged += OnItemChanged;
        }

        private void OnItemChanged(T item)
        {
            try
            {
                // 将整个列表序列化并保存
                string json = JsonConvert.SerializeObject(new List<T>(mValue));
                PlayerPrefs.SetString(mSaveKey, json);
            }
            catch (Exception e)
            {
                Debug.LogError($"Failed to serialize list data for key {mSaveKey}: {e.Message}");
            }
        }
    }
}
